<template>
  <div @click.stop>
    <div class="bg-[#FFFFFF] shadow-[0rem_0rem_0.63rem_0rem_rgba(0,0,0,0.1)] rounded-[1rem] p-4 w-full overflow-hidden">
      <template v-if="value">
        <template v-if="goodsList.length">
          <div class="flex flex-col gap-4">
            <div class="flex overflow-x-scroll gap-2">
              <div
                class="px-4 py-1 rounded-full border cursor-pointer"
                v-for="(i, k) in classificationList"
                :key="k"
                @click="switchTab(k)"
                :class="k == key ? 'text-[#FF4E33] bg-[#FFF4F0] border-[#FFF4F0] border-solid border-[1px]  ' : 'text-[#999999]'"
              >
                <span class="text-[0.88rem] font-medium whitespace-nowrap">
                  {{ i.title || '' }}
                </span>
              </div>
            </div>
            <div class="max-h-[70vh] overflow-y-scroll">
              <nuxt-link
                v-for="(i, k) in goodsList"
                :key="k"
                @click.native="closeSearch"
                :to="localePath(`/product/${i.code}`)"
                class="group flex gap-2 items-center py-3 cursor-pointer"
              >
                <!-- <div class="font-bold text-[0.88rem] w text-[#999999]">
                  {{ k + 1 }}
                </div> -->
                <div class="size-[3.5rem] border rounded-[0.75rem] overflow-hidden flex-none">
                  <img
                    :src="$globalFn.imgPrefixUrl(i.image, 'goods_thumb_1_1')"
                    alt="Product thumbnail"
                    title="View product details"
                    class="size-full group-hover:scale-110 object-cover duration-300"
                    loading="lazy"
                  />
                </div>
                <div class="flex flex-col justify-around">
                  <div class="flex gap-2 items-center">
                    <div class="font-medium text-[0.88rem] text-[#121212] line-clamp-2">
                      {{ i?.goods_name }}
                    </div>
                    <img
                      src="https://cd.sealmg.com/assets/img/discountLabel.png"
                      class="size-4"
                      alt="discountLabel"
                      title="discountLabel"
                      v-if="i.max_discount > 0"
                    />
                  </div>
                  <div class="font-medium text-[0.75rem] text-[#999999]">
                    {{ i?.region?.name }}
                  </div>
                </div>
              </nuxt-link>
            </div>
          </div>
        </template>
        <template v-if="!goodsList.length">
          <no-data class="*:!mt-0 *:!mb-0" :loading="loading"></no-data>
        </template>
      </template>
      <template v-if="!value">
        <div class="flex relative flex-col gap-4">
          <!-- <i
            @click.stop="deleteAll"
            class="el-icon-circle-close cursor-pointe absolute top-0 right-0 cursor-pointer"
          >
          </i> -->
          <template v-if="historicalList.length">
            <div class="flex justify-between items-center">
              <h2>{{ $t('pages.searchHistory') }}</h2>
              <i class="el-icon-delete cursor-pointer" @click.stop="deleteAll"></i>
            </div>
            <div class="flex flex-wrap gap-2">
              <nuxt-link
                class="bg-[#FAF9F9] rounded-[0.25rem] hover:bg-[#FAF9F9]/80 py-1 px-3 flex justify-center items-center cursor-pointer"
                v-for="(i, k) in historicalList"
                :key="k"
                :to="localePath(`/search?keywords=${i}`)"
                @click.native="closeSearch"
              >
                <span class="font-normal text-[0.75rem] text-[#666666] text-nowrap">
                  <!-- 只是需要8个字 -->
                  {{ geshi(i) }}
                </span>
              </nuxt-link>
            </div>
          </template>
          <template v-if="popularList.length">
            <h2>{{ $t('pages.hotList') }}</h2>
            <div class="max-h-[50vh] overflow-y-scroll">
              <nuxt-link
                v-for="(i, k) in popularList"
                :key="k"
                :to="localePath(`/product/${i.code}`)"
                @click.native="closeSearch"
                class="group flex gap-2 items-center py-3 cursor-pointer"
              >
                <div class="font-bold text-[0.88rem] text-[#999999] w-6">
                  {{ formattedNumber(k + 1) }}
                </div>
                <div class="size-[2.38rem] rounded-[0.38rem] border flex-none overflow-hidden">
                  <img
                    :src="$globalFn.imgPrefixUrl(i.image, 'goods_thumb_1_1')"
                    alt="Hot product thumbnail"
                    title="View popular product details"
                    class="size-full object-cover"
                    loading="lazy"
                  />
                </div>
                <div class="font-medium text-[0.88rem] group-hover:underline group-hover:underline-offset-4 text-[#121212]">
                  {{ i?.goods_name }}
                </div>
                <!--  -->
                <img
                  src="https://cd.sealmg.com/assets/img/discountLabel.png"
                  class="size-4"
                  alt="Discount badge"
                  title="Special offer available"
                  v-if="i.max_discount > 0"
                />
              </nuxt-link>
            </div>
          </template>
          <no-data :loading="loading2" v-if="!popularList.length"></no-data>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
  import { debounce } from '@/static/js/common'

  export default {
    name: 'h5search',
    data() {
      return {
        key: 0,
        classificationList: [],
        goodsList: [],
        limit: 9999,
        popularList: [],
        historicalList: [],
        loading2: true,
        loading: true
      }
    },
    props: {
      value: {
        type: String,
        default: ''
      },
      showSearch: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      value: {
        // immediate: true,
        deep: true,
        handler: debounce(function (newValue, oldValue) {
          this.goodsList = []
          this.classificationList = []
          this.getSearchList()
        }, 600)
      },
      showSearch: {
        // immediate: true,
        deep: true,
        handler(newValue, oldValue) {
          if (newValue) {
            this.getPopular()
            this.getHistory()
          }
        }
      }
    },
    created() {
      // if(this.)
    },
    beforeDestroy() {
      // 组件销毁前关闭弹框
      this.$emit('update:showSearch', false)
    },
    methods: {
      closeSearch() {
        this.$emit('update:showSearchD', false)
      },
      geshi(i) {
        //超出文字8个 加...
        if (i.length > 8) {
          return i.substring(0, 8) + '...'
        } else {
          return i
        }
      },
      getHistory() {
        let search = localStorage.getItem('history') || []
        if (search.length == 0) {
          this.historicalList = []
          return
        }
        this.historicalList = JSON.parse(search)
      },
      // jumpTo(item) {
      //   this.$parent.showSearchD = false;
      //   // this.value = "";
      //   let type = item.type;
      //   if (!type) {
      //     this.$router.push({
      //       path: this.localePath(`/game/${item.code}`),
      //     });
      //   }
      //   if (type == 1) {
      //     this.$router.push({
      //       path: this.localePath(`/cards/${item.code}`),
      //     });
      //   }
      //   if (type == 2) {
      //     this.$router.push({
      //       path: this.localePath(`/game/${item.code}`),
      //     });
      //   }
      // },
      formattedNumber(num) {
        return num.toString().padStart(2, '0')
      },
      getSearchList() {
        this.loading = true
        this.$axios
          .get(`/api/goods/search?keywords=${this.value}`)
          .then(result => {
            this.classificationList = result
            if (result.length == 0) {
              this.loading = false

              return
            }
            this.getGoodsList()
          })
          .catch(err => {})
      },
      getPopular() {
        this.loading2 = true
        this.$axios
          .get(`/api/goods/index?is_hot=1&page=1&limit=10`)
          .then(result => {
            this.popularList = result
            this.loading2 = false
          })
          .catch(err => {
            this.loading2 = false
          })
      },
      getGoodsList() {
        const typeMap = {
          0: `/api/game/index?page=1&limit=${this.limit}&keywords=${this.value}`,
          1: `/api/goods/index?type=1&limit=${this.limit}&keywords=${this.value}`,
          2: `/api/goods/index?type=2&limit=${this.limit}&keywords=${this.value}`
        }
        const baseUrl = typeMap[this.classificationList[this.key].type] || ''
        this.$axios
          .get(baseUrl)
          .then(res => {
            this.goodsList = res || []
            this.loading = false
          })
          .catch(err => {
            this.loading = false
            this.goodsList = []
          })
      },
      switchTab(k) {
        this.key = k
        this.getGoodsList()
      },
      deleteAll() {
        // 删除历史记录
        // this.$parent.showSearchD = false;
        // this.$emit("update:showSearchD", false);
        localStorage.removeItem('history')
        this.getHistory()
      }
    }
  }
</script>
<style lang="less" scoped></style>
